package cn.nkpro.elcube.co.http;

import cn.nkpro.elcube.exception.NkHttpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public abstract class NkAbstractHttpClient {


    protected NkHttpResponse doPost(String url, Map<String,String> headers, String data){
        try (CloseableHttpClient client = getClient()) {
            HttpPost post = new HttpPost(url);

            if(headers!=null){
                headers.forEach(post::setHeader);
            }

            if(data!=null){
                post.setEntity(new StringEntity(data));
            }

            if(log.isInfoEnabled())
                log.info("SpEL Post "+ url);

            CloseableHttpResponse response = client.execute(post);

            return new NkHttpResponse(response.getStatusLine().getStatusCode(),
                    Arrays.stream(response.getAllHeaders())
                            .map(Objects::toString)
                            .collect(Collectors.toList()),
                    EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new NkHttpException(e.getMessage(),e);
        }
    }

    private static CloseableHttpClient getClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(X509Certificate[] arg0,String arg1) {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] arg0,String arg1) {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom()
                    .setSSLSocketFactory(ssf).build();
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    }
}
